package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"net"
	"sync"
	"time"
	"traning/grpc_stream/proto"
)

const PORT = ":50052"

type server struct {
	GET string
}

func (this *server) GetStream(reqdata *proto.StreamReqData, serStr proto.Greeter_GetStreamServer) error {
	i := 0
	for {
		i ++
		_ = serStr.Send(&proto.StreamResData{
			Data: fmt.Sprintf("%v",time.Now().Unix()),
		})
		time.Sleep(time.Second)
		if i > 3 {
			break
		}
	}
	return nil
}

func (this *server) PullStream(cliStr proto.Greeter_PullStreamServer) error {
	for {
		if req, err := cliStr.Recv(); err != nil {
			fmt.Println(err)
			break
		} else {
			fmt.Println(req.Data)
		}
	}
	return nil
}

func (this *server) AllStream(allStr proto.Greeter_AllStreamServer) error {
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for {
			res, _ := allStr.Recv()
			fmt.Printf("AllStream recive %v \n" , res)
		}
	}()

	go func() {
		defer wg.Done()
		for {
			allStr.Send(&proto.StreamResData{Data: fmt.Sprintf("我是服务器\n")})
			time.Sleep(time.Second)
		}
	}()

	wg.Wait()
	return nil
}

func main() {
	interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		fmt.Println("接收到一个新请求")
		return handler(ctx, req)
	}
	opt := grpc.UnaryInterceptor(interceptor)
	lis, err := net.Listen("tcp", PORT)
	if err != nil {
		panic(err)
	}
	s := grpc.NewServer(opt)
	proto.RegisterGreeterServer(s, &server{})

	err = s.Serve(lis)
}